﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace LightCAD.Core
{
    public class Polygon2d : ICurve2d
    {
        private bool? _isConvex;
        private Box2d? _boundingBox;

        public Curve2dType Type => Curve2dType.Polygon2d;

        public Vector2d[] Points { get; set; }

        [JsonIgnore]
        public bool IsClosed => true;

        [JsonIgnore]
        public object Source { get; set; }

        public string Name { get; set; }


        public void Copy(ICurve2d src)
        {
            var polygon = src as Polygon2d;
            this.Points = polygon.Points.Clone<Vector2d>();
            this.Name = polygon.Name;
        }
        public ICurve2d Clone()
        {
            var newObj = new Polygon2d();
            newObj.Copy(this);
            return newObj;
        }
        object ICloneable.Clone()
        {
            return this.Clone();
        }

        public void Reset()
        {
            _boundingBox = null;
            _isConvex = null;
        }
        public Box2d BoundingBox
        {
            get
            {
                if (_boundingBox == null)
                {
                    _boundingBox = Box2d.Empty;
                    _boundingBox = _boundingBox.Value.ExpandByPoints(Points);
                }
                return _boundingBox.Value;
            }
        }
      

        public void ApplyMatrix(Matrix3d matrix)
        {
            for (var i = 0; i < Points.Length; i++)
            {
                Points[i] = matrix.MultiplyPoint(Points[i]);
            }
        }
        public Polygon2d Multiply(Matrix3d matrix)
        {
            var newPoly = new Polygon2d { Points = new Vector2d[this.Points.Length] };
            for (var i = 0; i < Points.Length; i++)
            {
                newPoly.Points[i] = matrix.MultiplyPoint(Points[i]);
            }
            return newPoly; 
        }
        public bool IsConvex
        {
            get
            {
                if(_isConvex == null)
                {
                    _isConvex = GeoUtils.IsConvexPolygon(this.Points);
                }
                return _isConvex.Value;
            }
        }


        public bool Contains(Vector2d point)
        {
            return GeoUtils.IsPointInPolygon(point, this.Points);
        }

      
    }
}
